package cn.kgc.servlet;

import cn.kgc.pojo.User;
import cn.kgc.service.UserService;
import cn.kgc.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Rock
 * @create 2020-08-17 11:24
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserService userService=new UserServiceImpl();
        //编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //接收参数
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        User user = userService.login(userName, password);
        if (user != null){
            //把当前用户存储到session中
            req.getSession().setAttribute("user", user);
            //重定向
            //req.getRequestDispatcher("/main.jsp").forward(req,resp);
            resp.sendRedirect("main.jsp");
        }else {//非法用户
            //提示+后退
            resp.getWriter().write("<script language='javascript'>alert('登录失败');history.back();</script>");

        }
    }
}
